import React, { useState, useEffect } from 'react';
import { 
  NavBar, 
  Avatar, 
  Grid, 
  Badge, 
  Divider,
  Button,
  Tag
} from 'antd-mobile';
import { 
  BankcardOutline,
  TruckOutline,
  MessageOutline,
  HeartOutline,
  GiftOutline,
  PhonebookOutline,
  SetOutline,
  RightOutline,
  FolderOutline,
  PayCircleOutline,
  SystemQRcodeOutline,
  FillinOutline,
  CouponOutline
} from 'antd-mobile-icons';
import { useNavigate } from 'react-router-dom';
import axios from '../../axios';
import './Com/My.css';

// 订单数据类型 - 用于提货码功能
interface Product {
  _id: string;
  productId: string;
  quantity: number;
}

interface Order {
  _id: string;
  id: string;
  userId: string;
  orderId: string;
  products: Product[];
  totalQuantity: number;
  status: string;
  orderTime: string;
  paymentMethod: string;
  deliveryAddress: string;
  caption: string;
  pickupCode?: string|null;
  completedTime?: string|null;
  refundReason?: string|null;
  refundAmount?: number|null;
  refundTime?: string|null;
  tradeNo?: string;
  paidTime?: string|null;
  outTradeNo?: string;
  createdAt: string;
  updatedAt: string;
}

// 优惠券数据类型
interface Coupon {
  _id: string;
  id: string;
  userId: string;
  couponId: string;
  name: string;
  type: string;
  discount: number;
  minAmount: number;
  category: string;
  status: string;
  startTime: string;
  endTime: string;
  description: string;
  createdAt: string;
  updatedAt: string;
  usedTime?: string|null;
  usedOrderId?: string;
}

// 用户数据类型 - 更新后的结构，不包含订单和优惠券
interface UserInfo {
  _id: string;
  id: string;
  userName: string;
  nickname: string;
  passWord: string;
  avatar: string;
  phone: string;
  email: string;
  vipLevel: number;
  points: number;
  verified: boolean;
  gender: string;
  city: string;
  registerTime: string;
  lastLoginTime: string;
  status: string;
  wallet?: {
    balance: number;
    redPackets: number;
    bonus: number;
  };
  createdAt: string;
  updatedAt: string;
}

// 订单统计数据类型
interface OrderStats {
  unpaid: number;
  undelivered: number;
  pickup: number;
  uncommented: number;
  refund: number;
}

// 优惠券统计数据类型
interface CouponStats {
  total: number;
  available: number;
  used: number;
  expired: number;
}

const My: React.FC = () => {
  const navigate = useNavigate();
  const [userInfo, setUserInfo] = useState<UserInfo | null>(null);
  const [orderStats, setOrderStats] = useState<OrderStats>({
    unpaid: 0,
    undelivered: 0,
    pickup: 0,
    uncommented: 0,
    refund: 0
  });
  const [couponStats, setCouponStats] = useState<CouponStats>({
    total: 0,
    available: 0,
    used: 0,
    expired: 0
  });
  const [loading, setLoading] = useState(true);
  const [userId, setUserId] = useState<string | null>(null);

  const handleBack = (): void => {
    navigate(-1);
  };

  // 从API获取用户数据
  useEffect(() => {
    const fetchUserData = async () => {
      try {
        setLoading(true);
        
        // 从 localStorage 获取用户ID
        const yonghuId = localStorage.getItem('yonghuId');
        
        if (!yonghuId) {
          console.error('未找到用户ID，请重新登录');
          setLoading(false);
          return;
        }
        
        // 存储用户ID到状态变量
        setUserId(yonghuId);
        
        // 获取用户基本信息
        const userResponse = await axios.get(`http://localhost:3000/hy/yonghu/${yonghuId}`);
        
        if (userResponse.data.code === 200 && userResponse.data.data) {
          const userData = userResponse.data.data.user;
          // 确保avatar字段有完整的URL
          if (userData.avatar && !userData.avatar.startsWith('http')) {
            userData.avatar = `http://localhost:3000${userData.avatar}`;
          }
          setUserInfo(userData);
          console.log('用户数据:', userResponse.data.data);
          
          // 设置订单统计
          if (userResponse.data.data.orders) {
            console.log('订单列表:', userResponse.data.data.orders);
            setOrderStats({
              unpaid: userResponse.data.data.orders.filter((order: Order) => order.status === '待付款').length,
              undelivered: userResponse.data.data.orders.filter((order: Order) => order.status === '待发货').length,
              pickup: userResponse.data.data.orders.filter((order: Order) => order.status === '待提货').length,
              uncommented: userResponse.data.data.orders.filter((order: Order) => order.status === '待评价').length,
              refund: userResponse.data.data.orders.filter((order: Order) => order.status === '退款中' || order.status === '退款失败' || order.status === '已退款').length
            });
          }
          
          // 设置优惠券统计
          if (userResponse.data.data.coupons) {
            console.log('优惠券列表:', userResponse.data.data.coupons);
            setCouponStats({
              total: userResponse.data.data.coupons.length,
              available: userResponse.data.data.coupons.filter((coupon: Coupon) => coupon.status === '可使用').length,
              used: userResponse.data.data.coupons.filter((coupon: Coupon) => coupon.status === '已使用').length,
              expired: userResponse.data.data.coupons.filter((coupon: Coupon) => coupon.status === '已过期').length
            });
          }
        } else {
          console.error('获取用户数据失败:', userResponse.data.message);
        }

      } catch (error) {
        console.error('获取数据失败:', error);
      } finally {
        setLoading(false);
      }
    };

    fetchUserData();
  }, []);

  // 订单相关操作
  const orderItems = [
    {
      key: '待付款',
      title: '待付款',
      icon: <BankcardOutline />,
      count: orderStats.unpaid,
      color: '#ff4d4f'
    },
    {
      key: '待发货',
      title: '待发货',
      icon: <TruckOutline />,
      count: orderStats.undelivered,
      color: '#faad14'
    },
    {
      key: '待提货',
      title: '待提货',
      icon: <FolderOutline />,
      count: orderStats.pickup,
      color: '#52c41a'
    },
    {
      key: '待评价',
      title: '待评价',
      icon: <MessageOutline />,
      count: orderStats.uncommented,
      color: '#1890ff'
    },
    {
      key: '退款/售后',
      title: '退款/售后',
      icon: <PayCircleOutline />,
      count: orderStats.refund,
      color: '#f5222d'
    }
  ];

  // 活动中心
  const activityItems = [
    {
      key: 'vip',
      title: '会员中心',
      icon: <GiftOutline />,
      color: '#faad14'
    },
    {
      key: 'redpacket',
      title: '天天领红包',
      icon: <HeartOutline />,
      color: '#ff4757'
    }
  ];

  // 我的服务
  const serviceItems = [
    {
      key: 'pickup',
      title: '提货码',
      icon: <SystemQRcodeOutline />,
      color: '#52c41a'
    },
    {
      key: 'contact',
      title: '联系客服',
      icon: <PhonebookOutline />,
      color: '#1890ff'
    },
    {
      key: 'feedback',
      title: '投诉/建议',
      icon: <FillinOutline />,
      color: '#722ed1'
    },
    {
      key: 'settings',
      title: '设置',
      icon: <SetOutline />,
      color: '#8c8c8c'
    }
  ];

  const handleOrderClick = (type: string): void => {
    // 将中文状态转换为英文参数，保持URL简洁
    const typeMap: { [key: string]: string } = {
      '待付款': 'unpaid',
      '待发货': 'undelivered',
      '待提货': 'pickup',
      '待评价': 'uncommented',
      '退款/售后': 'refund'
    };
    
    const paramType = typeMap[type] || type;
    navigate(`/my/order?type=${paramType}`, {
      state: {
        userInfo: userInfo
      }
    });
  };

  const handleActivityClick = (key: string): void => {
    switch(key) {
      case 'vip':
        navigate('/my/vipqy', {
          state: {
            userInfo: userInfo
          }
        });
        break;
      case 'redpacket':
        navigate('/my/red', {
          state: {
            userInfo: userInfo
          }
        });
        break;
      default:
        console.log(`点击活动: ${key}`);
    }
  };

  // 我的服务
  const handleServiceClick = async (key: string): Promise<void> => {
    switch(key) {
      case 'pickup': {
        try {
          // 从用户数据中筛选待提货的订单
          const response = await axios.get(`http://localhost:3000/hy/yonghu/${userId}`);
          const pickupOrders = response.data.code === 200 && response.data.data.orders 
            ? response.data.data.orders.filter((order: Order) => order.status === '待提货')
            : [];
          
          navigate('/my/ma', {
            state: {
              userInfo: {
                userId: userId,
                nickname: userInfo?.nickname,
                avatar: userInfo?.avatar,
                phone: userInfo?.phone,
                email: userInfo?.email,
                vipLevel: userInfo?.vipLevel,
                points: userInfo?.points,
              },
              pickupCodes: pickupOrders.map((order: Order) => ({
                orderId: order.orderId,
                productIds: order.products.map((p: Product) => p.productId).join(', '),
                pickupCode: order.pickupCode,
                orderTime: order.orderTime,
                deliveryAddress: order.deliveryAddress,
                quantity: order.totalQuantity
              }))
            }
          });
        } catch (error) {
          console.error('获取提货码数据失败:', error);
          navigate('/my/ma', {
            state: {
              userInfo: {
                userId: userId,
                nickname: userInfo?.nickname,
                avatar: userInfo?.avatar,
                phone: userInfo?.phone,
                email: userInfo?.email,
                vipLevel: userInfo?.vipLevel,
                points: userInfo?.points,
              },
              pickupCodes: []
            }
          });
        }
        break;
      }
      case 'contact':
        navigate('/my/ai', {
          state: {
            userInfo: userInfo
          }
        });        
        break;
      case 'feedback':
        navigate('/my/complaince', {
          state: {
            userInfo: userInfo
          }
        });
        break;
      case 'settings':
        navigate('/my/setting', {
          state: {
            userInfo: userInfo
          }
        });
        break;
      default:
        console.log(`点击服务: ${key}`);
    }
  };

  const handleEditProfile = (): void => {
    navigate('/my/editinfo', {
      state: {
        userInfo: userInfo
      }
    });
  };

  const handleCouponsClick = (): void => {
    navigate('/my/coupon', {
      state: {
        userInfo: userInfo
      }
    });
  };

  if (loading) {
    return <div className="loading">正在加载...</div>;
  }

  if (!userInfo) {
    return <div className="error">用户信息获取失败</div>;
  }

  return (
    <div className="my-page">
      <NavBar onBack={handleBack} className="my-navbar">
        我的
      </NavBar>

      {/* 用户信息区域 */}
      <div className="user-info-section">
        <div className="user-basic-info">
          <Avatar 
            src={userInfo?.avatar || ''} 
            className="user-avatar"
          />
          <div className="user-details">
            <div className="user-name-area">
              <span className="user-nickname">{userInfo?.nickname || '未设置昵称'}</span>
            </div>
            <div className="user-phone">
              {userInfo?.phone ? userInfo.phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2') : '未设置手机号'}
            </div>
          </div>
          <Button 
            size="small" 
            className="edit-btn"
            onClick={handleEditProfile}
          >
            编辑资料
          </Button>
        </div>

        {/* 卡券 */}
        <div className="wallet-section">
          <Grid columns={1} gap={8}>
            <Grid.Item>
              <div className="coupon-item" onClick={handleCouponsClick}>
                <div className="coupon-left">
                  <CouponOutline className="coupon-icon" />
                  <div className="coupon-info">
                    <div className="coupon-label">优惠券（{couponStats.total}）</div>
                  </div>
                </div>
                <RightOutline className="coupon-arrow" />
              </div>
            </Grid.Item>
          </Grid>
        </div>
      </div>

      {/* 订单状态 */}
      <div className="order-section">
        <div className="section-header">
          <span className="section-title">我的订单</span>
          <Button style={{fontSize: '0.35rem'}}
            fill="none" 
            size="small"
            onClick={() => navigate('/my/order', {
              state: {
                userInfo: userInfo
              }
            })}
          >
            查看全部 <RightOutline />
          </Button>
        </div>
        
        <Grid columns={5} gap={8}>
          {orderItems.map((item) => (
            <Grid.Item key={item.key}>
              <div 
                className="order-item" 
                onClick={() => handleOrderClick(item.key)}
              >
                <Badge 
                  content={item.count || 0} 
                  className="order-badge"
                >
                  <div className="order-icon" style={{ color: item.color }}>
                    {item.icon}
                  </div>
                </Badge>
                <div className="order-title">{item.title}</div>
              </div>
            </Grid.Item>
          ))}
        </Grid>
      </div>

      <Divider />

      {/* 活动中心 */}
      <div className="activity-section">
        <div className="section-header">
          <span className="section-title">活动中心</span>
        </div>
        
        <Grid columns={2} gap={8}>
          {activityItems.map((item) => (
            <Grid.Item key={item.key}>
              <div 
                className="activity-item" 
                onClick={() => handleActivityClick(item.key)}
              >
                <div className="activity-icon" style={{ color: item.color }}>
                  {item.icon}
                </div>
                <div className="activity-title">{item.title}</div>
              </div>
            </Grid.Item>
          ))}
        </Grid>
      </div>

      <Divider />

      {/* 我的服务 */}
      <div className="service-section">
        <div className="section-header">
          <span className="section-title">我的服务</span>
        </div>
        
        <Grid columns={4} gap={8}>
          {serviceItems.map((item) => (
            <Grid.Item key={item.key}>
              <div 
                className="service-item" 
                onClick={() => handleServiceClick(item.key)}
              >
                <div className="service-icon" style={{ color: item.color }}>
                  {item.icon}
                </div>
                <div className="service-title">{item.title}</div>
              </div>
            </Grid.Item>
          ))}
        </Grid>
      </div>
    </div>
  );
};

export default My;
